package com.chuanyang.driverh.mainstart.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.chuanyang.driverh.BaseApplication;
import com.chuanyang.driverh.R;
import com.chuanyang.driverh.base.BaseListAdapter;
import com.chuanyang.driverh.base.BaseListFragment;
import com.chuanyang.driverh.mainhome.BidHallActivity;
import com.chuanyang.driverh.mainhome.FleetJoinActivity;
import com.chuanyang.driverh.mainhome.GetOrderListActivity;
import com.chuanyang.driverh.mainhome.MoneyFollowDriverActivity;
import com.chuanyang.driverh.mainhome.QualifyingActivity;
import com.chuanyang.driverh.mainhome.WaitTransActivity;
import com.chuanyang.driverh.mainstart.adapter.AdPagerAdapter;
import com.chuanyang.driverh.mainstart.adapter.AdViewPager;
import com.chuanyang.driverh.mainstart.adapter.IncvocePriceAdapterLeader;
import com.chuanyang.driverh.responseresult.DriverInfoData;
import com.chuanyang.driverh.responseresult.InvoceOrderResult;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.eventbus.RefleshDriverInfoEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;
import com.chuanyang.driverh.utils.widget.ViewPagerScroller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import okhttp3.Call;


public class HomePagerDriverFragment extends BaseListFragment {
    private View mview;
    //广告
    private ViewPager vp_main_ad;//广告的轮播图
    private ArrayList<AdViewPager> mList_AD;
    private LinearLayout ll_ad_dot;
    private int centerValue;
    private AdPagerAdapter pagerAdapter;
    //    private TextView tv_ad;
    private Handler handlerChange = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            vp_main_ad.setCurrentItem(vp_main_ad.getCurrentItem() + 1);
            handlerChange.sendEmptyMessageDelayed(0, 3000);
        }
    };

    //按钮
    private LinearLayout ll_receive_order,ll_money_follow,ll_daiyun,ll_toubiao,ll_jingjia,ll_jiameng;

    private DriverInfoData driverInfoData;

    @Override
    public BaseListAdapter createAdapter() {
        return new IncvocePriceAdapterLeader(getActivity());
    }
    @Override
    public void initView(View view) {
        super.initView(view);
       /* mview = View.inflate(getContext(), R.layout.common_frag_home_header_driver, null);
        mAdapter = createAdapter();


        mlistview.addHeaderView(mview);
        mlistview.setAdapter(mAdapter);*/

        ll_receive_order = (LinearLayout) mview.findViewById(R.id.ll_receive_order);
        ll_money_follow = (LinearLayout) mview.findViewById(R.id.ll_money_follow);
        ll_daiyun = (LinearLayout) mview.findViewById(R.id.ll_daiyun);
        ll_toubiao = (LinearLayout) mview.findViewById(R.id.ll_toubiao);
        ll_jingjia = (LinearLayout) mview.findViewById(R.id.ll_jingjia);
        ll_jiameng = (LinearLayout) mview.findViewById(R.id.ll_jiameng);

        setPager();//初始化轮播图片

    }


    @Override
    protected View initHeaderView() {
        mview = View.inflate(getContext(), R.layout.common_frag_home_header_driver, null);
        return mview;

    }

    @Override
    protected void initData() {
        driverInfoData= BaseApplication.getInstance().getDriverInfo();
       /* if (driverInfoData==null){
            BaseApplication.getInstance().getDriverInfoFromNet();
        }else {
            getData(true);
        }*/

        BaseApplication.getInstance().getDriverInfoFromNet();
    }
    @Override
    protected void initListener() {
        ll_receive_order.setOnClickListener(this);
        ll_money_follow.setOnClickListener(this);
        ll_daiyun.setOnClickListener(this);
        ll_toubiao.setOnClickListener(this);
        ll_jingjia.setOnClickListener(this);
        ll_jiameng.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_receive_order:
                startActivity(GetOrderListActivity.class);
                break;
            case R.id.ll_money_follow:
                startActivity(MoneyFollowDriverActivity.class);
                break;
            case R.id.ll_daiyun:
                startActivity(WaitTransActivity.class);
                break;
            case R.id.ll_toubiao:
                startActivity(QualifyingActivity.class);
                break;
            case R.id.ll_jingjia:
                startActivity(BidHallActivity.class);
                break;
            case R.id.ll_jiameng:
                //判断司机有没有加盟，如果code=102说明没有加盟
                selectBusinessByDriverInfo();
                break;
        }
    }

    private void setPager() {
        initPager();
        initDots();
        viewPagerChangePage();
        initViewPagerChangeListener();
    }

    private void initPager() {
        vp_main_ad = (ViewPager) mview.findViewById(R.id.vp_main_ad);
        ll_ad_dot = (LinearLayout) mview.findViewById(R.id.ll_ad_dot);
        centerValue = Integer.MAX_VALUE / 2;
        mList_AD = new ArrayList<>();
        mList_AD.add(new AdViewPager(R.mipmap.banner0, "nihao"));
        mList_AD.add(new AdViewPager(R.mipmap.banner1, "nihao"));
        mList_AD.add(new AdViewPager(R.mipmap.banner2, "nihao"));
        mList_AD.add(new AdViewPager(R.mipmap.banner3, "nihao"));
        //广告轮播方法
    }
    /***
     * 初始化广告页点的方法
     */
    private void initDots() {
        for (int i = 0; i < mList_AD.size(); i++) {
            View view = new View(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
            if (i != 0) {
                params.leftMargin = 20;
            }
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.dot_select);
            ll_ad_dot.addView(view);
        }
    }

    private void viewPagerChangePage() {
        //服务器好了之后首先进行网络数据请求
        pagerAdapter = new AdPagerAdapter(getActivity(), mList_AD);
        vp_main_ad.setAdapter(pagerAdapter);
        ViewPagerScroller scroller = new ViewPagerScroller(getActivity());
        scroller.setScrollDuration(2000);
        scroller.initViewPagerScroll(vp_main_ad);
        int center = (centerValue - centerValue) % mList_AD.size();
        vp_main_ad.setCurrentItem(center);
        updateIntroAndDot();
        if (mList_AD.size() > 1) {
            handlerChange.sendEmptyMessageDelayed(0, 3000);
        }
    }
    /***
     * 当ViewPager切换时，改变下面的文本
     */
    private void updateIntroAndDot() {
        int currentPage = vp_main_ad.getCurrentItem() % mList_AD.size();
        //int currentPage = mAdViewPager.getCurrentItem();
        //mPageTextView.setText(mList_AD.get(currentPage).getUrl());
        //设置点
        for (int i = 0; i < mList_AD.size(); i++) {
            ll_ad_dot.getChildAt(i).setEnabled(i == currentPage);
        }
    }
    //当广告页的ViewPager切换时下面的字也要跟着改变
    private void initViewPagerChangeListener() {
        vp_main_ad.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                //当ViewPager变换时改变下面的字
                updateIntroAndDot();
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }




    //获取竞价列表
    private void getData(final boolean isFlush) {

        DialogUtil.showLoadingDialog(getActivity(),"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("page", mCurrentPage + "");
        params.put("length", "10");
        params.put("driverId", SharedPrefUtil.getUserId());
        if (driverInfoData.getDriver() != null && driverInfoData.getDriver().getDriverType() != null) {
            if (driverInfoData.getDriver().getDriverType() == 2)//车
            {
                params.put("transPortWay", "1");
            } else {
                params.put("transPortWay", "2");
            }
        }
        MyHttpUtil.bidOrder(getActivity(),params, new MyCallback<InvoceOrderResult>(getActivity(),new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(getActivity(), "网络异常，请稍后再试");
                springView.onFinishFreshAndLoad();
            }
            @Override
            public void onSuccess(InvoceOrderResult result, int id) {
                if (result.getCode() == ConstUtil.OK && result.getData()!=null && result.getData().getData()!=null &&result.getData().getData().size()>0) {
                    setDataResult(result.getData().getData());
                }else{
                    if (isFlush){
                        mAdapter.clear();
                        mAdapter.notifyDataSetChanged();
                    }
                    springView.onFinishFreshAndLoad();
                    PrintUtil.toast(getActivity(),result.getMsg());
                }
            }
        });

    }

    //获取加盟的列表
    private void selectBusinessByDriverInfo(){

        DialogUtil.showLoadingDialog(getActivity(),"加载中...");
        Map<String,Object> paramssss =new HashMap<String, Object>();
        paramssss.put("page", "1");
        paramssss.put("length", "10");
        paramssss.put("driverId", SharedPrefUtil.getUserId());

        MyHttpUtil.selectBusinessByDriverInfo(getActivity(),paramssss, new MyCallback<Result>(getActivity(),new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {

            }
            @Override
            public void onSuccess(Result result, int id) {

                LogUtils.d(result.getCode()+result.getMsg());
                if(result.getCode() == 102){//未加盟
                    Intent intent = new Intent(getActivity(),FleetJoinActivity.class);
                    intent.putExtra("jiameng","102");
                    intent.putExtra("fleet","2");
                    startActivity(intent);
                }else if(result.getCode() == 100){//已加盟
                    Intent intent = new Intent(getActivity(),FleetJoinActivity.class);
                    intent.putExtra("jiameng","100");
                    intent.putExtra("fleet","2");
                    startActivity(intent);
                }else {

                }

            }
        });

    }



    public void onEventMainThread(RefleshDriverInfoEvent event) {
        if (event.isRefleshDriverInfo()) {
            bidOrderRefresh();
        }
    }

    public void onEventMainThread(RefleshFragEvent event) {
        if (event.getIndex()==0  ){
            onRefresh();
        }
    }

    public void bidOrderRefresh(){
        mCurrentPage = 1;
        driverInfoData= BaseApplication.getInstance().getDriverInfo();
        if (driverInfoData!=null){
            getData(true);
        }else{
            BaseApplication.getInstance().getDriverInfoFromNet();
        }
    }
    @Override
    protected void onForceRefresh() { bidOrderRefresh();    }
    @Override
    public void onRefresh() {
        bidOrderRefresh();
    }
    @Override
    public void onGetMore() {
        getData(false);
    }

    @Override
    protected boolean isLoadMore() {
        return true;
    }
    @Override
    protected boolean isPullToRefresh() {
        return true;
    }






}
